package reliability.ui;

import reliability.model.GraphModel;
import reliability.model.GraphModelEvent;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;

public class DefaultReliabilityPanel
    extends InfoPanelComponent
{
    NumericField nodeReliabilityField;
    NumericField edgeReliabilityField;

    public DefaultReliabilityPanel(GraphModel model)
    {
        super(model);
        setPreferredSize(new Dimension(290, 120));
        setBorder(BorderFactory.createTitledBorder("Надежность элементов по умолчанию"));
        FlowLayout layout = new FlowLayout();
        layout.setAlignment(FlowLayout.LEFT);
        setLayout(layout);

        JLabel nodeReliabilityLabel = new JLabel("Для узлов");
        nodeReliabilityLabel.setFont(InfoPanel.DEFAULT_FONT);
        add(nodeReliabilityLabel);
        nodeReliabilityField = new NumericField(model.getDefaultNodeReliability(), 23);
        nodeReliabilityField.addFocusListener(this);
        add(nodeReliabilityField);

        JLabel edgeReliabilityLabel = new JLabel("Для связей");
        edgeReliabilityLabel.setFont(InfoPanel.DEFAULT_FONT);
        add(edgeReliabilityLabel);
        edgeReliabilityField = new NumericField(model.getDefaultEdgeReliability(), 23);
        edgeReliabilityField.addFocusListener(this);
        add(edgeReliabilityField);
    }

    public void focusLost(FocusEvent focusEvent)
    {
        Object eventSource = focusEvent.getSource();
        if (eventSource.equals(nodeReliabilityField))
        {
            double nodeReliability = getDoubleValue(nodeReliabilityField.getValue());
            model.setDefaultNodeReliability(nodeReliability);
        }
        else if (eventSource.equals(edgeReliabilityField))
        {
            double edgeReliability = getDoubleValue(edgeReliabilityField.getValue());
            model.setDefaultEdgeReliability(edgeReliability);
        }
    }

    public void graphModelChanged(GraphModelEvent event)
    {
        if (event.getId() == GraphModelEvent.GRAPH_INIT)
        {
            nodeReliabilityField.setValue(model.getDefaultNodeReliability());
            edgeReliabilityField.setValue(model.getDefaultEdgeReliability());
        }
    }
}
